import { NextFunction, Request, Response } from 'express';
import loginSer from './service'
import { encrypt, genToken } from '../../utils/common';
import Base from '../../common/controller/base';
import userService from '../../common/services/user';
import { LoginOpt } from './types';

/**
 * 登录相关
 */
class LoginController extends Base {
    /**
     * 测试
     * @param _req 
     * @param res 
     */
    test = (_req: Request, res: Response) => {
        // console.log(resolveToken(req.headers.authorization || ''))
        setTimeout(() => {
            this.success(res, { msg: '测试4', data: '' })
        }, 2000)
    }

    /**
     * 登录
     * @param req 
     * @param res 
     */
    login = async (req: Request, res: Response, next: NextFunction) => {
        // 1. 判断账号密码  是否正确
        const info = req.body as LoginOpt;
        // 获取用户账号密码
        let { username, password } = info

        password = encrypt(String(password));

        try {
            // 判断用户是否注册了
            const isExist = await userService.isUserExist(username)
            if (!isExist) return next({ msg: '该用户还没注册哦' })

            // 检验用户密码
            const [isCorr, user] = await loginSer.vertifyuserAndPass(username, password)
            if (!isCorr) return next({ msg: '用户名或密码或用户对应的角色错误' })

            // 获取用户信息
            const token = genToken({ ...user })
            
            this.success(res, { msg: '登录成功', data: { ...user, token } })
        } catch (e) {
            next({ msg: '服务器出错', code: 500 })
        }
    }
}

export default new LoginController()